package com.tdd.api.server.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.tdd.api.server.adapter.model.ApprovalCenterList;
import com.tdd.api.server.domain.result.wx.service.PushReturn;
import com.tdd.api.server.entity.TbUserNotice;
import com.tdd.api.server.entity.TbUserOpen;
import com.tdd.api.server.service.ITbUserNoticeService;
import com.tdd.api.server.service.ITbUserOpenService;
import com.tdd.api.server.service.IWeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import com.tdd.api.server.adapter.CrmApiService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

@Slf4j
@Component
public class ScheduledService {


    @Resource
    private ITbUserOpenService userOpenService;

    @Resource
    private ITbUserNoticeService noticeService;

    @Resource
    private IWeChatService weChatService;

    @Resource
    private CrmApiService crmApiService;

    public final DateTimeFormatter dateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    //**10分钟执行一次
    @Scheduled(fixedRate = 60 * 1000)
    public void automaticRenewalJOB() {
        //查询可推送的用户
        List<TbUserOpen> users = userOpenService.pushUser();
        if (CollUtil.isEmpty(users)) {
            log.info("无推送用户 >> {}", LocalDateTime.now());
            return;
        }

        for (TbUserOpen user : users) {

            if (StrUtil.isEmpty(user.getOpenId())) {
                log.info("OPEN ID IS NULL >> {}", user.getUsername());
                user.setPushStatus(-1);
                userOpenService.updateById(user);
                return;
            }

            List<ApprovalCenterList> approval = crmApiService.getApprovalList(user.getToken());

            if (CollUtil.isEmpty(approval)) {
                log.info("无推送数据 >> {}", user.getUsername());
                return;
            }

            Optional<ApprovalCenterList> one = approval.stream()
                    .filter(x -> StrUtil.isNotEmpty(x.getSubmission_time()))
                    .filter(x -> LocalDateTime.parse(x.getSubmission_time(), dateTime).isAfter(user.getPushTime()))
                    .findFirst();

            if (one.isPresent()) {
                ApprovalCenterList n = one.get();
                log.info("PUSH >> {} >> {} >>{}", user.getUsername(), user.getOpenId(), n.getWorkflow().getName());
                PushReturn re = weChatService.pushExamineMessage(
                        user.getOpenId(),
                        "您有一条审批待处理，请及时处理",
                        n.getWorkflow().getName(),
                        n.getSubmitter().getName(),
                        n.getSubmission_time()
                );
                TbUserNotice notice = new TbUserNotice();
                notice.setNoticeDate(LocalDateTime.now());
                notice.setNoticeContent(JSONUtil.toJsonStr(re));
                notice.setStatus(-1);
                notice.setUserId(user.getUserId());
                if (re != null && re.getErrcode() == 0) {
                    notice.setStatus(1);
                    user.setPushStatus(9);
                    user.setPushTime(LocalDateTime.now());
                } else {
                    user.setPushStatus(-1);
                    user.setPushTime(LocalDateTime.now());
                }
                userOpenService.updateById(user);
                noticeService.save(notice);
            }
        }
    }

}
